﻿using System;
using System.Collections.Concurrent;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading;
using Raven.Abstractions.Commands;
using Raven.Abstractions.Data;
using Raven.Client;
using Raven.Json.Linq;
using Topics.Radical.ComponentModel.Messaging;
using Topics.Radical.Helpers;
using Topics.Radical.Validation;
using SampleApp.MvcBackend.ComponentModel;

namespace SampleApp.MvcBackend.Runtime
{
	class CommitDispatchConsumer : DispatchConsumer<Commit>
	{
		readonly IMessageBroker broker;
		readonly IDocumentStore documentSessionFactory;

		public CommitDispatchConsumer( IMessageBroker broker, IDocumentStore documentSessionFactory )
		{
			Ensure.That( broker ).Named( () => broker ).IsNotNull();
			Ensure.That( documentSessionFactory ).Named( () => documentSessionFactory ).IsNotNull();

			this.broker = broker;
			this.documentSessionFactory = documentSessionFactory;
		}

		protected override void Dispatch( Commit commit )
		{
			foreach ( var @event in commit.Events )
			{
				this.broker.Dispatch( this, @event );
			}

			var dbCmd = this.documentSessionFactory.DatabaseCommands;
			dbCmd.Patch( commit.Id, new[] { new PatchRequest
			{
				Type = PatchCommandType.Set,
				Name = ReflectionHelper.GetPropertyName<Commit>( c => c.IsDispatched ),
				Value = RavenJToken.Parse( "true" )
			} } );
		}
	}
}
